#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/cmsi/send_mail.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a bking.company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import json, base64
from django import forms
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, ListField, DefaultBooleanField
from common.base_utils import str_bool
from .toolkit import configs, tools, send_mail_with_smtp

class SendMail(Component, SetupConfMixin):
    """
    apiLabel 发送邮件
    apiMethod POST
    
    ### 功能描述
    
    发送邮件
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段               |  类型      | 必选   |  描述      |
    |--------------------|------------|--------|------------|
    | receiver           |  string    | 否     | 邮件接收者，包含邮件完整地址，多个以逗号分隔，若receiver、receiver__username同时存在，以receiver为准 |
    | receiver__username |  string    | 否     | 邮件接收者，包含用户名，用户需在蓝鲸平台注册，多个以逗号分隔，若receiver、receiver__username同时存在，以receiver为准 |
    | sender             |  string    | 否     | 发件人 |
    | title              |  string    | 是     | 邮件主题 |
    | content            |  string    | 是     | 邮件内容 |
    | cc                 |  string    | 否     | 抄送人，包含邮件完整地址，多个以逗号分隔 |
    | cc__username       |  string    | 否     | 抄送人，包含用户名，用户需在蓝鲸平台注册，多个以逗号分隔，若cc、cc__username同时存在，以cc为准 |
    | body_format        |  string    | 否     | 邮件格式，包含'Html', 'Text'，默认为'Html' |
    | is_content_base64  |  bool      | 否     | 邮件内容是否base64编码，默认False，不编码，请使用base64.b64encode方法编码 |
    
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "receiver": "admin@bking.com",
        "sender": "admin@bking.com",
        "title": "This is a Test",
        "content": "<html>Welcome to Blueking</html>",
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "邮件发送成功。",
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME
    host = configs.host
    contact_way = 'email'
    smtp_timeout = 10

    class Form(BaseComponentForm):
        sender = forms.CharField(label=u'发件人', required=False)
        receiver = ListField(label=u'邮件接收人', required=False)
        receiver__username = ListField(label=u'邮件接收人', required=False)
        cc = ListField(label=u'抄送人', required=False)
        cc__username = ListField(label=u'抄送人', required=False)
        title = forms.CharField(label=u'邮件主题', required=True)
        content = forms.CharField(label=u'邮件内容', required=True)
        is_content_base64 = DefaultBooleanField(label=u'内容是否base64编码', default=False, required=False)
        body_format = forms.CharField(label=u'邮件格式', required=False)

        def clean(self):
            data = self.cleaned_data
            if not (data['receiver'] or data['receiver__username']):
                raise forms.ValidationError(u'邮件接收人[receiver、receiver__username]不能同时为空。')
            if data['receiver']:
                data['receiver__username'] = None
            if data['cc']:
                data['cc__username'] = None
            if data['is_content_base64']:
                try:
                    data['content'] = base64.b64decode(data['content'])
                except:
                    pass

            return data

    def handle(self):
        self.smtp_host = getattr(self, 'smtp_host', '') or getattr(configs, 'smtp_host', '')
        self.smtp_port = getattr(self, 'smtp_port', None) or getattr(configs, 'smtp_port', None)
        self.smtp_user = getattr(self, 'smtp_user', '') or getattr(configs, 'smtp_user', '')
        self.smtp_pwd = getattr(self, 'smtp_pwd', '') or getattr(configs, 'smtp_pwd', '')
        self.mail_sender = getattr(self, 'mail_sender', '') or getattr(configs, 'mail_sender', '')
        self.smtp_usessl = getattr(self, 'smtp_usessl', '') or getattr(configs, 'smtp_usessl', False)
        self.smtp_usessl = str_bool(self.smtp_usessl)
        self.dest_url = getattr(self, 'dest_url', '') or getattr(configs, 'dest_url', '')
        data = self.request.kwargs
        if data['receiver']:
            tools.validate_receiver(data['receiver'], contact_way=self.contact_way)
        if data['cc']:
            tools.validate_receiver(data['cc'], contact_way=self.contact_way)
        if data['receiver__username'] or data['cc__username']:
            user_data = tools.get_receiver_with_username(receiver__username=data['receiver__username'], cc__username=data['cc__username'], contact_way=self.contact_way)
            data.update(user_data)
        if not data['sender']:
            data['sender'] = self.mail_sender
        if self.dest_url:
            result = self.outgoing.http_client.request_by_url('POST', self.dest_url, data=json.dumps(data))
            if result['result'] and data.get('_extra_user_error_msg'):
                result = {'result': False,'message': u'部分用户邮件发送失败。%s' % data['_extra_user_error_msg']
                   }
            self.response.payload = result
        else:
            if self.smtp_host:
                smtp_client = send_mail_with_smtp.SMTPClient(smtp_host=self.smtp_host, smtp_port=int(self.smtp_port or 25), smtp_user=self.smtp_user, smtp_pwd=self.smtp_pwd, smtp_usessl=self.smtp_usessl, smtp_timeout=self.smtp_timeout)
                result = smtp_client.send_mail(data)
                if result['result'] and data.get('_extra_user_error_msg'):
                    result = {'result': False,'message': u'部分用户邮件发送失败。%s' % data['_extra_user_error_msg']
                       }
                self.response.payload = result
            else:
                self.response.payload = {'result': False,'message': u'未完成接口，需要组件负责人进行完善'}
        return
